<script setup lang="ts">
import { onLoad } from '@dcloudio/uni-app'
import { getHomeBannerAPI, getHomeCategoryAPI, getHomeHotAPI } from '@/services/home'
import { ref } from 'vue'
import type { BannerItem, CategoryItem, HotItem } from '@/types/home'
import CategoryPanel from './components/CategoryPanel.vue'
import HotPanel from './components/HotPanel.vue'
import CustomNav from './components/CustomNavbar.vue'
import type { XtxGuessInstance } from '@/types/components'
import PageSkeleton from './components/PageSkeleton.vue'
// 获取猜你喜欢组件实例
const guessRef = ref<XtxGuessInstance>()
const BannerList = ref<BannerItem[]>([])
const getHomeBannerData = async () => {
  const res = await getHomeBannerAPI()
  BannerList.value = res.result
}

const CategoryList = ref<CategoryItem[]>([])
const getHomeCategoryData = async () => {
  const res = await getHomeCategoryAPI()
  CategoryList.value = res.result
}

const HotList = ref<HotItem[]>([])
const getHomeHotData = async () => {
  const res = await getHomeHotAPI()
  console.log(res)
  HotList.value = res.result
}
// 滚动触底事件
const onScrolltolower = () => {
  guessRef.value?.getMore()
}

const isLoading = ref(false)
// 首次进入页面
onLoad(async () => {
  isLoading.value = true
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  isLoading.value = false
})

const isRefreshing = ref(false)
const onRefresherrefresh = async () => {
  // 开始刷新
  isRefreshing.value = true
  // await getHomeBannerData()
  // await getHomeCategoryData()
  // await getHomeHotData()
  // 重置猜你喜欢列表
  guessRef.value?.resetData()
  await Promise.all([getHomeBannerData(), getHomeCategoryData(), getHomeHotData()])
  // 关闭刷新动画
  isRefreshing.value = false
}
</script>

<template>
  <!-- 导航栏 -->
  <CustomNav />
  <!-- 启用滚动刷新功能的滚动视图 -->
  <PageSkeleton v-if="isLoading" />
  <template v-else>
    <scroll-view
      refresher-enabled
      @refresherrefresh="onRefresherrefresh"
      :refresher-triggered="isRefreshing"
      class="scroll-view"
      scroll-y
      @scrolltolower="onScrolltolower"
    >
      <!-- 轮播图 -->
      <XtxSwiper :list="BannerList" />
      <!-- 分类 -->
      <CategoryPanel :list="CategoryList" />
      <!-- 热门商品 -->
      <HotPanel :list="HotList" />
      <XtxGuess ref="guessRef" />
    </scroll-view>
  </template>
</template>

<style lang="scss">
page {
  background-color: #f7f7f7;
  height: 100%;
  display: flex;
  flex-direction: column;
}
.scroll-view {
  flex: 1;
}
</style>
